$(function() {
    var indexObj = new RoleIndex();
    indexObj._init();
});

function RoleIndex() {

    var me = this;
    var record;
    var moduleOptions = [];
    var editFormModuleSelect2;

    this._init = function() {

        bindEvents();

        initDataTable();

        setValidation();
    };

    function bindEvents() {
        
        loadModuleOptions(function() {
            var searchFormModuleSelect2 = $('#searchForm #moduleSelect').select2({
                placeholder : '请选择', // 占位字符
                allowClear : true, // 允许清除已选项
                minimumResultsForSearch: -1,
                data : moduleOptions
            });
            searchFormModuleSelect2.val(null).trigger("change");

            editFormModuleSelect2 = $('#editRoleForm #moduleSelect').select2({
                placeholder : '请选择', // 占位字符
                allowClear : true, // 允许清除已选项
                minimumResultsForSearch: -1,
                data : moduleOptions
            });
            editFormModuleSelect2.val(null).trigger("change");
        });

        $('#searchBtn').on('click', function() {
            console.log('search');
            refreshDataTable();
        });

        $('#addBtn').on('click', function() {
            record = {};
            popupModal();
        });

        $('#roleModal').on('show.bs.modal', function(e) {
            console.log('onshow');
        });

        $('#roleModal #saveBtn').on('click', function(e) {
            saveRecord();
        });

        $('#roleDataTable').delegate('.editBtn', 'click', function() {
            editRecord($(this).attr('row'));
        });

        $('#roleDataTable').delegate('.deleteBtn', 'click', function() {
            deleteRecord($(this).attr('rid'));
        });

    }

    function loadModuleOptions(callback) {
        var requestParam = {
            iDisplayStart : 0,
            iDisplayLength : 20,
            sEcho : 1,
        };
        $.ajax({
            url : contextPath + '/module/getPageInfo', // 请求的API地址
            type : 'GET',
            dataType : 'json',
            data : $.param(requestParam),
            success : function(data) {
                console.log(data);
                moduleOptions = $.map(data.aaData, function(obj) {
                    obj.id = obj.id;
                    obj.text = obj.name;
                    return obj;
                });
                console.log(moduleOptions);

                if (callback) {
                    callback();
                }
            }
        });
    }

    function initDataTable() {
        $('#roleDataTable')
                .dataTable(
                        {
                            "bProcesing" : true,
                            "bServerSide" : true,
                            "bLenthChange" : false,
                            "bFilter" : false,
                            "iDisplayLength" : 10,
                            "iDisplayStart" : 0,
                            "sEcho" : 1,
                            "bSort" : false,
                            "sAjaxSource" : contextPath + "/role/getPageInfo",
                            "fnServerParams" : function(aoData) {
                                aoData.push({
                                    "name" : "moduleId",
                                    "value" : $("#searchForm #moduleSelect").val(),
                                }, {
                                    "name" : "codeKeyword",
                                    "value" : $("#searchForm #codeKeyword").val(),
                                }, {
                                    "name" : "nameKeyword",
                                    "value" : $("#searchForm #nameKeyword").val(),
                                });
                            },
                            "pagingType" : "full_numbers",
                            "oLanguage" : {
                                "sLengthMenu" : "显示 _MENU_ 条记录",
                                "sSearch" : "搜索",
                                "oPaginate" : {
                                    "sFirst" : "首页",
                                    "sLast" : "末页",
                                    "sPrevious" : "上一页",
                                    "sNext" : "下一页",
                                },
                                "sEmptyTable" : "无记录",
                                "sInfo" : "共 _TOTAL_条记录，当前显示 (_START_-_END_)",
                                "sInfoFiltered" : " 共 _MAX_ 条",
                                "sLoadingRecords" : "加载中..."
                            },
                            "aoColumns" : [
                                    {
                                        data : 'id',
                                        bVisible : false
                                    },
                                    {
                                        data : "moduleCode"
                                    },
                                    {
                                        data : "moduleName"
                                    },
                                    {
                                        data : "index0"
                                    },
                                    {
                                        data : "code"
                                    },
                                    {
                                        data : "name"
                                    },
                                    {
                                        data : "remark"
                                    },
                                    {
                                        data : null,
                                        render : function(data, type, row, meta) {
                                            var html = '<div><a href="javascript:void(0);" class="editBtn margin-right-5" row="'
                                                    + meta.row
                                                    + '">编辑</a><a href="javascript:void(0);" class="deleteBtn" rid="'
                                                    + row.id + '">删除</a></div>';
                                            return html;
                                        },
                                    }, ]
                        });
    }

    function refreshDataTable() {
        $("#roleDataTable").dataTable().fnDraw(false);
    }

    function editRecord(row) {
        record = $("#roleDataTable").DataTable().row(row).data();
        popupModal();
    }

    function popupModal() {
        $('#roleModal').modal('show');
        fillForm();
    }

    function fillForm() {
        console.log(record);
        fillJsForm('#editRoleForm', record);
    }

    function setValidation() {
        $('#editRoleForm').validate({
            rules : {
                'data.moduleId' : {
                    required : true
                },
                'data.index0' : {
                    required : true,
                    digits : true,
                    max : 50
                },
                'data.code' : {
                    required : true,
                    maxlength : 20
                },
                'data.name' : {
                    required : true,
                    maxlength : 20
                },
                'data.remark' : {
                    maxlength : 100
                },
            },
            errorElement : "span",
            errorPlacement : function(error, element) {
                error.addClass("help-block");
                if (element.prop("type") === "checkbox") {
                    error.insertAfter(element.parent("label"));
                } else {
                    error.insertAfter(element);
                }
            },
            highlight : function(element, errorClass, validClass) {
                $(element).parents(".col-sm-10").addClass("has-error").removeClass("has-success");
            },
            unhighlight : function(element, errorClass, validClass) {
                $(element).parents(".col-sm-10").addClass("has-success").removeClass("has-error");
            }
        });
    }

    function saveRecord() {
        var valid = $('#editRoleForm').valid();
        console.log('validated: ' + valid);

        if (valid) {
            record = $("#editRoleForm").jsForm("get");
            console.log(record);
            var json = JSON.stringify(record);

            $.ajax({
                url : contextPath + '/role/save',
                type : 'POST',
                dataType : 'json',
                contentType : 'application/json',
                data : json,
                success : function(data) {
                    record = null;
                    if (data.success) {
                        alert('保存成功');

                        $('#roleModal').modal('hide');
                        refreshDataTable();
                    } else {
                        alert('保存失败: ' + data.errorMessage);
                    }
                }
            });
        }
    }

    function deleteRecord(id) {
        console.log(id);
        if (!confirm('确定删除吗？')) {
            return false;
        } else {
            $.ajax({
                url : contextPath + '/role/delete?id=' + id,
                type : 'DELETE',
                dataType : 'json',
                contentType : 'application/json',
                success : function(data) {
                    if (data.success) {
                        alert('删除成功');
                        refreshDataTable();
                    } else {
                        alert('保存失败: ' + data.errorMessage);
                    }
                }
            });
            return true;
        }
    }

}
